package com.xhq.tools.rsa;

import javax.crypto.Cipher;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * @author huiny
 * @since 2021/8/14 23:06
 */
public class RsaEncDec {
    public static String encrypt(String data, String publicKeyBase64Content) throws GeneralSecurityException {
        return encrypt(data, publicKeyBase64Content, null);
    }

    public static String encrypt(String data, String publicKeyBase64Content, PaddingModelEnum paddingModelEnum)
            throws GeneralSecurityException {
        var publicKey = RsaKeyHelper.getPublicKeyFromBase64String(publicKeyBase64Content);
        return encrypt(data, publicKey, paddingModelEnum);
    }

    public static String encrypt(String data, PublicKey publicKey) throws GeneralSecurityException {
        return encrypt(data, publicKey, null);
    }

    public static String encrypt(String data, PublicKey publicKey, PaddingModelEnum paddingModelEnum)
            throws GeneralSecurityException {
        /* 可选的填充方式：
            RSA/ECB/PKCS1Padding,
            RSA/ECB/OAEPWithSHA-1ANDMGF1PADDING,
            RSA/ECB/OAEPWithSHA-256ANDMGF1PADDING,
            RSA/ECB/OAEPWITHSHA-512ANDMGF1PADDING
         */
        var cipherName = getCipherName(paddingModelEnum);
        Cipher cipher = Cipher.getInstance(cipherName);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return Base64Helper.encode(cipher.doFinal(data.getBytes()));
    }

    public static String decrypt(String data, String privateKeyDerContent) throws GeneralSecurityException {
        return decrypt(data, privateKeyDerContent, null);
    }

    public static String decrypt(String data, String privateKeyDerContent, PaddingModelEnum paddingModelEnum)
            throws GeneralSecurityException {
        var privateKey = RsaKeyHelper.getPrivateKeyFromDerString(privateKeyDerContent);
        return decrypt(data, privateKey, paddingModelEnum);
    }


    public static String decrypt(String data, PrivateKey privateKey) throws GeneralSecurityException {
        return decrypt(data, privateKey, null);
    }

    public static String decrypt(String data, PrivateKey privateKey, PaddingModelEnum paddingModelEnum)
            throws GeneralSecurityException {
        var cipherName = getCipherName(paddingModelEnum);
        Cipher cipher = Cipher.getInstance(cipherName);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return new String(cipher.doFinal(Base64Helper.decode(data)));
    }

    public static String getCipherName(PaddingModelEnum paddingModelEnum) {
        return "RSA/ECB/" + (paddingModelEnum == null ?
                PaddingModelEnum.OAEP_WITH_SHA256_AND_MGF1_PADDING.getValue() :
                paddingModelEnum.getValue());
    }

}
